package com.example.custom.rpc.handler;

import com.example.custom.rpc.common.Invocation;
import com.example.custom.rpc.register.LocalRegister;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author liyuncong
 * @version 1.0
 * @file HttpServerHandler
 * @brief HttpServerHandler
 * @details HttpServerHandler
 * @date 2022-11-02
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2022-11-02               liyuncong          Created
 */
public class HttpServerHandler {

    public void handler(HttpServletRequest req, HttpServletResponse resp) {
        // 处理请求 接口、方法、方法参数
        try {
            final Invocation invocation = (Invocation) new ObjectInputStream(req.getInputStream()).readObject();
            final String interfaceName = invocation.getInterfaceName();

            final Class classImpl = LocalRegister.getImpl(interfaceName);
            final Method method = classImpl.getMethod(invocation.getMethodName(), invocation.getParameterTypes());
            final String result = (String) method.invoke(classImpl.getDeclaredConstructor().newInstance(), invocation.getParameters());

            IOUtils.write(result, resp.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }


    }
}
